
var CACHE_NAME = 'my-site-cache-v1';
var urlsToCache = [
  // '/',
  '/pwaCache.css',
  '/pwaCache.js',
  // '/src/index.css'
];

self.addEventListener('install', function(event) {
  // Perform install steps
  console.log('install')
  event.waitUntil(
    caches.open(CACHE_NAME)
      .then(function(cache) {
        console.log('Opened cache',cache);
        return cache.addAll(urlsToCache);
      })
  );
});


self.addEventListener('fetch', function(event) {
  // console.log('fetch event',event)
  event.respondWith(
    caches.match(event.request)
      .then(function(response) {
        // Cache hit - return response
        if (response) {
          console.log('response',response)
          return response;
        }

       

        var fetchRequest = event.request.clone();
        return fetch(fetchRequest).then(
          function(response) {
            // Check if we received a valid response
            if(!response || response.status !== 200 || response.type !== 'basic') {
              return response;
            }

            // IMPORTANT:Clone the response. A response is a stream
            // and because we want the browser to consume the response
            // as well as the cache consuming the response, we need
            // to clone it so we have two streams.
            // 如果通过检查，则克隆响应。 这样做的原因在于，该响应是数据流， 
            // 因此主体只能使用一次。 由于我们想要返回能被浏览器使用的响应，并将其传递到缓存以供使用，
            // 因此需要克隆一份副本。我们将一份发送给浏览器，另一份则保留在缓存。
            var responseToCache = response.clone();
            // console.log(responseToCache)

            caches.open(CACHE_NAME)
              .then(function(cache) {
                cache.put(event.request, responseToCache);
              });

            return response;
          }
        );
      })
    );
});


self.addEventListener('activate', function(event) {
  console.log('activate1')
  var cacheAllowlist = ['pages-cache-v1', 'blog-posts-cache-v1'];

  event.waitUntil(
    caches.keys().then(function(cacheNames) {
      // console.log('===activate',cacheNames)
      return Promise.all(
        cacheNames.map(function(cacheName) {
          console.log('----',cacheName)
          if (cacheAllowlist.indexOf(cacheName) === -1) {
            return caches.delete(cacheName);
          }
        })
      );
    })
  );
});